package com.jyxd.web.controller.user;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.jyxd.web.data.common.Result;
import com.jyxd.web.data.user.Access;
import com.jyxd.web.data.user.Role;
import com.jyxd.web.data.user.User;
import com.jyxd.web.data.user.UserType;
import com.jyxd.web.hiscz.service.HisDictionaryService;
import com.jyxd.web.service.assessment.basic.CommonSettingService;
import com.jyxd.web.service.user.AccessService;
import com.jyxd.web.service.user.RoleService;
import com.jyxd.web.service.user.UserService;
import com.jyxd.web.service.user.UserTypeService;
import com.jyxd.web.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.InetAddress;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "用户相关相关接口")
@RestController
@RequestMapping(value = "/user")
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private AccessService accessService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private CommonSettingService commonSettingService;

    @Autowired
    private UserTypeService userTypeService;

    @Autowired
    private HisDictionaryService hisDictionaryService;


    /**
     * 增加一条平台用户表记录
     *
     * @return
     */
    @ApiOperation("增加一条平台用户表记录")
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "新增失败");
        try {
            if (map != null && map.containsKey("status") && userService.queryDataByWorkNumber(map) == null) {
                User user = new User();
                user.setId(UUIDUtil.getUUID());
                user.setPassword("e10adc3949ba59abbe56e057f20f883e");//密码默认123456
                user.setCreateTime(new Date());
                user.setStatus((int) map.get("status"));
                user.setWorkNumber(map.get("workNumber").toString());
                user.setLoginName(map.get("loginName").toString());
                user.setRoleId(map.get("roleId").toString());
                user.setSex((int) map.get("sex"));
                user.setUserName(map.get("userName").toString());
                //从session中获取user,  set TenantId
                User loginUser = (User) session.getAttribute("user");
                user.setTenantId(loginUser.getTenantId());
                user.setDeptCode(loginUser.getTenantId());

                // user.setIsShedual((int) map.get("isShedual"));
                if (StringUtils.isNotEmpty(map.get("simplicity").toString())) {
                    user.setSimplicity(map.get("simplicity").toString());
                }
                if (StringUtils.isNotEmpty(map.get("userTypeCode").toString())) {
                    user.setUserTypeCode(map.get("userTypeCode").toString());
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (StringUtils.isNotEmpty(map.get("enterTime").toString())) {
                    user.setEnterTime(sdf.parse(map.get("enterTime").toString()));
                }
                if (StringUtils.isNotEmpty(map.get("exitTime").toString())) {
                    user.setExitTime(sdf.parse(map.get("exitTime").toString()));
                }
                //处理手写签名
                if (StringUtils.isNotEmpty(map.get("signImgStr").toString())) {
                    String signStr = map.get("signImgStr").toString();
                    String[] split = signStr.split(",");
                    String imgType = Base64Util.subString(split[0], "/", ";");
                    String signImgName = UUIDUtil.getUUID() + "." + imgType;
                    String path = "D:\\signImg";
                    Base64Util.GenerateImage(split[1], path, signImgName);//base64转为图片 存入本地
                    InetAddress localHost = InetAddress.getLocalHost();
                    String ip = localHost.getHostAddress();//获取本机ip
                    user.setSignPath("http://" + ip + ":8080/" + signImgName);
                }
                userService.insert(user);
                json.put("msg", "新增成功");
                json.put("code", HttpCode.OK_CODE.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("增加一条平台用户表记录:" + e);
        }
        return json.toString();
    }

    /**
     * 更新平台用户表状态
     *
     * @param map
     * @return
     */
    @ApiOperation("更新平台用户表状态")
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "修改失败");
        if (map != null && map.containsKey("id") && map.containsKey("status")) {
            User user = userService.queryData(map.get("id").toString());
            if (user != null) {
                user.setStatus((int) map.get("status"));
                userService.update(user);
                json.put("msg", "修改成功");
                json.put("code", HttpCode.OK_CODE.getCode());
            } else {
                return json.toString();
            }
        }
        return json.toString();
    }

    /**
     * 编辑平台用户表记录
     *
     * @param map
     * @return
     */
    @ApiOperation("编辑平台用户表记录")
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        try {
            if (map != null && map.containsKey("id") && map.containsKey("status")) {
                User user = userService.queryData(map.get("id").toString());
                if (user != null) {
                    user.setStatus((int) map.get("status"));
                    user.setWorkNumber(map.get("workNumber").toString());
                    user.setLoginName(map.get("loginName").toString());
                    user.setRoleId(map.get("roleId").toString());
                    user.setSex((int) map.get("sex"));
                    user.setUserName(map.get("userName").toString());

                    User loginUser = (User) session.getAttribute("user");
                    user.setTenantId(loginUser.getTenantId());


                    //user.setIsShedual((int) map.get("isShedual"));
                    if (StringUtils.isNotEmpty(map.get("simplicity").toString())) {
                        user.setSimplicity(map.get("simplicity").toString());
                    }
                    if (StringUtils.isNotEmpty(map.get("userTypeCode").toString())) {
                        user.setUserTypeCode(map.get("userTypeCode").toString());
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (StringUtils.isNotEmpty(map.get("enterTime").toString())) {
                        user.setEnterTime(sdf.parse(map.get("enterTime").toString()));
                    }
                    if (StringUtils.isNotEmpty(map.get("exitTime").toString())) {
                        user.setExitTime(sdf.parse(map.get("exitTime").toString()));
                    }
                    //处理手写签名
                    if (StringUtils.isNotEmpty(map.get("signImgStr").toString())) {
                        //先判断此用户原来有没有签名图片路径，如果有，删除图片
                        if (StringUtils.isNotBlank(user.getSignPath())) {
                            File file = new File(user.getSignPath());
                            file.delete();
                        }
                        String signStr = map.get("signImgStr").toString();
                        String[] split = signStr.split(",");
                        String imgType = Base64Util.subString(split[0], "/", ";");
                        String signImgName = UUIDUtil.getUUID() + "." + imgType;
                        String path = "D:\\signImg";
                        Base64Util.GenerateImage(split[1], path, signImgName);//base64转为图片 存入本地
                        InetAddress localHost = InetAddress.getLocalHost();
                        String ip = localHost.getHostAddress();//获取本机ip
                        user.setSignPath("http://" + ip + ":8080/" + signImgName);
                    }
                    userService.update(user);
                    json.put("msg", "编辑成功");
                    json.put("code", HttpCode.OK_CODE.getCode());
                } else {
                    return json.toString();
                }
            }
        } catch (Exception e) {
            logger.info("编辑平台用户表记录:" + e);
        }
        return json.toString();
    }

    /**
     * 删除平台用户表记录
     *
     * @param map
     * @return
     */
    @ApiOperation("删除平台用户表记录")
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        if (map != null && map.containsKey("id")) {
            User user = userService.queryData(map.get("id").toString());
            if (user != null) {
                user.setStatus(-1);
                userService.update(user);
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "删除成功");
            } else {
                return json.toString();
            }
        }
        return json.toString();
    }

    /**
     * 重置用户密码为123456
     *
     * @param map
     * @return
     */
    @ApiOperation("重置用户密码为123456")
    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    public String resetPassword(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "重置失败");
        if (map != null && map.containsKey("id")) {
            User user = userService.queryData(map.get("id").toString());
            if (user != null) {
                user.setPassword("e10adc3949ba59abbe56e057f20f883e");//密码123456
                userService.update(user);
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "重置成功");
            } else {
                return json.toString();
            }
        }
        return json.toString();
    }

    /**
     * 根据主键id查询平台用户表记录
     *
     * @param map
     * @return
     */
    @ApiOperation("根据主键id查询平台用户表记录")
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        if (map != null && map.containsKey("id")) {
            User user = userService.queryData(map.get("id").toString());

            if (user != null) {
                json.put("data", JSONObject.fromObject(user));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询平台用户表列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @ApiOperation("根据条件分页查询平台用户表列表（也可以不分页）")
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        if (map != null && map.containsKey("start")) {
            int totalCount = userService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<User> list = userService.queryList(map);
        if (list != null && list.size() > 0) {
            json.put("data", JSONArray.fromObject(list));
        }

        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询平台用户表列表（也可以不分页）--多表查询
     *
     * @param map
     * @return
     */
    @ApiOperation("根据条件分页查询平台用户表列表（也可以不分页）--多表查询")
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @ResponseBody
    public String getList(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        User loginUser = (User) session.getAttribute("user");
        if (map == null) map = new HashMap<>();
        map.put("tenantId", loginUser.getTenantId());
        if (map != null && map.containsKey("start")) {
            int totalCount = userService.getNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<Map<String, Object>> list = userService.getList(map);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                List<Map<String, Object>> signList = new ArrayList<Map<String, Object>>();
                Map<String, Object> signMap = new HashMap<String, Object>();
                Map<String, Object> signMaps = new HashMap<String, Object>();
                signMap.put("url", list.get(i).get("sign_path").toString());
                signList.add(signMap);
                list.get(i).put("sign_path", signList);
            }
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonArrayValueProcessor());
            json.put("data", JSONArray.fromObject(list, jsonConfig));
            json.put("msg", "查询成功");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 用户登录接口
     *
     * @param map
     * @return
     */
    @ApiOperation("用户登录接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.LOGIN_FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "账号密码有误，请重新输入！");
        if (map != null && map.containsKey("password")) {
            map.put("password", MD5Util.string2MD5(map.get("password").toString()));
            User user = userService.queryUserByNameAndPassword(map);
            if (user != null) {
                JsonConfig jsonConfig = new JsonConfig();
                jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
                session.setAttribute("user", user);
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("roleId", user.getRoleId());
                List<Access> list = accessService.getList(hashMap);
                JSONArray jsonArray = new JSONArray();
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        jsonArray.add(list.get(i).getMenuCode());
                    }
                }
                json.put("menu", jsonArray);
                json.put("user", JSONObject.fromObject(user, jsonConfig));
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "登录成功");
            }
        }
        return json.toString();
    }

    /**
     * 用户退出登录接口
     *
     * @param
     * @return
     */
    @ApiOperation("用户退出登录接口")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public String logout(HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "退出登录失败！");
        session.invalidate();
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "退出登录成功");
        return json.toString();
    }

    /**
     * 床位信息--新增病人--根据条件查询医生或护士员工列表
     *
     * @param map
     * @return
     */
    @ApiOperation("床位信息--新增病人--根据条件查询医生或护士员工列表")
    @RequestMapping(value = "/getUserListByType", method = RequestMethod.POST)
    @ResponseBody
    public String getUserListByType(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        List<Map<String, Object>> list = userService.getUserListByType(map);
        if (list != null && list.size() > 0) {
            json.put("data", JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "查询成功");
        return json.toString();
    }

    /**
     * 用户登录成功后获取登录信息
     *
     * @param map
     * @return
     */
    @ApiOperation("用户登录成功后获取登录信息")
    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
    @ResponseBody
    public String getUser(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.LOGIN_FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "获取失败！");
        User user = (User) session.getAttribute("user");
        if (user != null) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
            JSONObject jsonObject = JSONObject.fromObject(user, jsonConfig);
            json.put("password", MD5Util.convertMD5(user.getPassword()));
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("roleId", user.getRoleId());
            List<Access> list = accessService.getList(hashMap);
            JSONArray jsonArray = new JSONArray();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    jsonArray.add(list.get(i).getMenuCode());
                }
            }
            jsonObject.put("menu", jsonArray);
            Role role = roleService.queryData(user.getRoleId());
            if (role != null) {
                JSONArray jsonArray1 = new JSONArray();
                jsonArray1.add(role.getRoleName());
                jsonObject.put("roles", jsonArray1);
            }
            //查询默认首页
            /**
             Map<String, Object> map1 = new HashMap<>();
             map1.put("settingType", "默认首页");
             List<CommonSetting> commonSetting = commonSettingService.getCommonSettingByType(map1);
             if (!CollectionUtils.isEmpty(commonSetting)) {
             json.put("homePage", commonSetting.get(0).getSettingContent());
             } else {
             json.put("homePage", "工作站");//默认为工作站
             }
             **/
            json.put("homePage", "工作站");//默认为工作站
            json.put("data", jsonObject);
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "获取成功");
        }
        return json.toString();
    }

    /**
     * 解锁 锁屏
     *
     * @param map
     * @return
     */
    @ApiOperation("解锁 锁屏")
    @RequestMapping(value = "/unlock", method = RequestMethod.POST)
    @ResponseBody
    public String unlock(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.LOGIN_FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());

        User user = (User) session.getAttribute("user");
        if (user != null && user.getPassword().equals(MD5Util.getMD5String(map.get("password").toString()))) {
            String url = (String) session.getAttribute("url");
            json.put("url", url);
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "解锁成功");
        }
        return json.toString();
    }

    /**
     * 锁屏
     *
     * @param map
     * @return
     */
    @ApiOperation("锁屏")
    @RequestMapping(value = "/lock", method = RequestMethod.POST)
    @ResponseBody
    public String lock(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.LOGIN_FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "锁屏失败！");
        if (StringUtils.isNotEmpty(map.get("url").toString())) {
            session.setAttribute("url", map.get("url").toString());
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "锁屏成功");
        }
        return json.toString();
    }

    /**
     * 修改密码
     *
     * @param map
     * @return
     */
    @ApiOperation("修改密码")
    @RequestMapping(value = "/updatePassword")
    @ResponseBody
    public String updatePassword(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "修改失败");
        if (map != null && map.containsKey("id") && map.containsKey("password") && map.containsKey("newPassword")) {
            User user = userService.queryData(map.get("id").toString());
            if (user != null) {
                if (user.getPassword().equals(MD5Util.string2MD5(map.get("password").toString()))) {
                    user.setPassword(MD5Util.string2MD5(map.get("newPassword").toString()));
                    userService.update(user);
                    json.put("code", HttpCode.OK_CODE.getCode());
                    json.put("msg", "修改成功");
                } else {
                    json.put("code", HttpCode.PASSWORD_ERROR_CODE.getCode());
                    json.put("msg", "原密码错误，请重新输入原密码！");
                }
            }
        }
        return json.toString();
    }

    /**
     * 根据用户类型查询用户列表
     *
     * @param map userTypeName
     * @return
     */
    @ApiOperation("根据用户类型查询用户列表")
    @RequestMapping(value = "/getUserListByUserType")
    @ResponseBody
    public String getUserListByUserType(@RequestBody(required = false) Map<String, Object> map, @RequestHeader(required = false, name = "tenantId") String tenantId) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "修改失败");
        logger.info("tenantId:{}",tenantId);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if(map == null) {
            map = new HashMap<>();
        }

        if (StrUtil.isNotEmpty(tenantId)) {
            map.put("deptCode", tenantId);
        }
        logger.info("map:{}",map);
        if (map.containsKey("userType")) {
            list = userService.getListSimple(map);
        } else {
            if (map.containsKey("userTypeName")) {
                UserType userType = userTypeService.queryDataByName(map);
                if (userType != null) {
                    map.put("userTypeCode", userType.getUserTypeCode());
                }
            }
            list = userService.getListSimple(map);
        }
        /**屏蔽查询太慢
         for (int i=0;i<list.size();i++){
         if (list.get(i).get("sign_path").equals("")){
         list.get(i).put("disabled",true);
         }else{
         list.get(i).put("disabled",false);
         }
         }**/
        if (list != null && list.size() > 0) {
            json.put("data", JSONArray.fromObject(list));
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "成功");
        }
        return json.toString();
    }


    /**
     * 查询护士信息列表
     *
     * @return
     */
    @ApiOperation("根据用户类型查询用户列表")
    @RequestMapping(value = "/getNurseList")
    @ResponseBody
    public String getNurseList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "修改失败");
        List<Map<String, Object>> nurseList = userService.getNurseList(map);
        //List<Map<String, Object>> nurseList = hisDictionaryService.getNurseList();
        if (nurseList != null && nurseList.size() > 0) {
            json.put("data", JSONArray.fromObject(nurseList));
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "成功");
        }
        return json.toString();
    }

    /**
     * 从his系统获取并更新用户数据
     *
     * @param map
     * @return
     */
    @ApiOperation("从his系统获取并更新用户数据")
    @RequestMapping(value = "/updateUserByHis", method = RequestMethod.POST)
    @ResponseBody
    public String updateUserByHis(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "失败");
        try {
            //查询本地数据库字典数据
            List<User> list = userService.queryUserList(map);
            //从his数据库视图中查询科室字典数据
            List<Map<String, Object>> hisList = userService.getUserByHis(map);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (hisList != null && hisList.size() > 0) {
                if (list != null && list.size() > 0) {
                    //如果数据库有数据则需要和his中获取的数据做比较再更新

                    ArrayList arrayList = new ArrayList();
                    for (int i = 0; i < list.size(); i++) {
                        arrayList.add(list.get(i).getWorkNumber());//工号唯一性
                    }

                    ArrayList arrayHisList = new ArrayList();
                    for (int i = 0; i < hisList.size(); i++) {
                        arrayHisList.add(hisList.get(i).get("user_id").toString());//工号唯一性
                    }

                    for (int i = 0; i < list.size(); i++) {
                        if (!arrayHisList.contains(list.get(i).getWorkNumber())) {
                            //如果his系统中数据 里 没有本地数据 则删除本地数据
                            list.get(i).setStatus(-1);
                            userService.update(list.get(i));
                        }
                    }

                    for (int i = 0; i < hisList.size(); i++) {
                        if (!arrayList.contains(hisList.get(i).get("user_id").toString())) {
                            //如果本地数据不包含 his系统数据 则新增数据
                            User user = new User();
                            user.setStatus(1);
                            user.setId(UUIDUtil.getUUID());
                            user.setUserName(hisList.get(i).get("user_name").toString());
                            user.setSimplicity(hisList.get(i).get("user_name").toString());
                            user.setLoginName(hisList.get(i).get("user_name").toString());
                            user.setPassword(hisList.get(i).get("password").toString());
                            user.setCreateTime(new Date());
                            user.setIsShedual(1);//是否参与排班（0：不参与 1：参与）
                            user.setUserTypeCode(hisList.get(i).get("user_type_code").toString());
                            user.setWorkNumber(hisList.get(i).get("user_id").toString());
                            user.setSex((int) hisList.get(i).get("sex"));
                            if (StringUtils.isNotEmpty(hisList.get(i).get("enter_time").toString())) {
                                user.setEnterTime(format.parse(hisList.get(i).get("enter_time").toString()));
                            }
                            if (StringUtils.isNotEmpty(hisList.get(i).get("exit_time").toString())) {
                                user.setExitTime(format.parse(hisList.get(i).get("exit_time").toString()));
                            }
                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("userTypeCode", hisList.get(i).get("user_type_code").toString());
                            Role role = roleService.queryDataByTypeCode(map1);
                            if (role != null) {
                                user.setRoleId(role.getId());
                            }
                            userService.insert(user);
                        }
                    }
                } else {
                    //直接将his获取的数据添加到本地数据库
                    for (int i = 0; i < hisList.size(); i++) {
                        User user = new User();
                        user.setStatus(1);
                        user.setId(UUIDUtil.getUUID());
                        user.setUserName(hisList.get(i).get("user_name").toString());
                        user.setSimplicity(hisList.get(i).get("user_name").toString());
                        user.setLoginName(hisList.get(i).get("user_name").toString());
                        user.setPassword(hisList.get(i).get("password").toString());
                        user.setCreateTime(new Date());
                        user.setIsShedual(1);//是否参与排班（0：不参与 1：参与）
                        user.setUserTypeCode(hisList.get(i).get("user_type_code").toString());
                        user.setWorkNumber(hisList.get(i).get("user_id").toString());
                        user.setSex((int) hisList.get(i).get("sex"));
                        if (StringUtils.isNotEmpty(hisList.get(i).get("enter_time").toString())) {
                            user.setEnterTime(format.parse(hisList.get(i).get("enter_time").toString()));
                        }
                        if (StringUtils.isNotEmpty(hisList.get(i).get("exit_time").toString())) {
                            user.setExitTime(format.parse(hisList.get(i).get("exit_time").toString()));
                        }
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("userTypeCode", hisList.get(i).get("user_type_code").toString());
                        Role role = roleService.queryDataByTypeCode(map1);
                        if (role != null) {
                            user.setRoleId(role.getId());
                        }
                        userService.insert(user);
                    }
                }
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "成功");
            }
        } catch (Exception e) {
            logger.info("updateUserByHis:" + e);
        }
        return json.toString();
    }


    public static void delete(File f) {
        //数组指向文件夹中的文件和文件夹
        File[] fi = f.listFiles();
        //遍历文件和文件夹
        for (File file : fi) {
            //如果是文件夹，递归查找
            if (file.isDirectory())
                delete(file);
            else if (file.isFile()) {
                //是文件的话，把文件名放到一个字符串中
                String filename = file.getName();
                //如果是“class”后缀文件，返回一个boolean型的值
                if (filename.endsWith("class")) {
                    System.out.println("成功删除：：" + file.getName());
                    //file.delete();
                }
            }
        }
    }

    /**
     * 获取用户相关信息通过工号
     *
     * @param map
     * @return
     */
    @ApiOperation("获取用户相关信息")
    @RequestMapping(value = "/findUserByWorkNumber", method = RequestMethod.POST)
    @ResponseBody
    public String findUserByWorkNumber(@RequestBody Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.LOGIN_FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "获取用户相关信息失败");
        if (map != null && map.containsKey("loginid")) {
            map.put("loginid", map.get("loginid").toString());
            User user = userService.findUserByWorkNumber(map);
            if (user != null) {
                JsonConfig jsonConfig = new JsonConfig();
                jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
                session.setAttribute("user", user);
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("roleId", user.getRoleId());
                List<Access> list = accessService.getList(hashMap);
                JSONArray jsonArray = new JSONArray();
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        jsonArray.add(list.get(i).getMenuCode());
                    }
                }
                json.put("menu", jsonArray);
                json.put("user", JSONObject.fromObject(user, jsonConfig));
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "获取用户相关信息成功");
            }
        }
        return json.toString();
    }

    @GetMapping("/add2icu/{loginName}")
    public Result<Void> updateDept(@PathVariable("loginName") String loginName, String deptCode) {
        if (StrUtil.isEmpty(deptCode)) {
            deptCode = "25";
        }

        Map<String, Object> map = Maps.newHashMap();
        map.put("loginName", loginName);
        map.put("deptCode", deptCode);
        userService.updateDeptCodeByLoginName(map);

        return Result.succeed("");
    }
}
